import time
from appium import webdriver
from selenium.webdriver.common.by import By

desired_caps = {
    'platformName': 'Android',                          # 被测手机是安卓
    'platformVersion': '10',                            # 手机安卓版本
    'deviceName': 'xxx',                                # 设备名，安卓手机可以随意填写
    'appPackage': 'com.hpbr.bosszhipin',                # 启动APP Package名称
    'appActivity': '.module.launcher.WelcomeActivity',  # 启动Activity名称
    'unicodeKeyboard': True,                            # 使用自带输入法，输入中文时填True
    'resetKeyboard': True,                              # 执行完程序恢复原来输入法
    'noReset': True,                                    # 不要重置App
    'newCommandTimeout': 6000,
    'automationName': 'UiAutomator2'
}

def main():
    def driverSwipe():
        driver.swipe(start_x=width / 2, start_y=1300, end_x=width / 2, end_y=950, duration=1000)

    def driverBack(id):
        driver.find_element(By.ID, id).click()

    # 连接Appium Server，初始化自动化环境
    driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

    # 设置缺省等待时间
    driver.implicitly_wait(10)

    # 获取屏幕的尺寸
    width = driver.get_window_size()['width']
    height = driver.get_window_size()['height']

    # 如果弹框存在，点击暂不
    promptBox = driver.find_elements(By.ID, "negative")
    if promptBox:
        promptBox.click()

    # 工作筛选条件
    a = '测'

    # 点最新
    driver.find_elements(By.ID,"tv_tab_label")[2].click()

    while True:

        driverSwipe()
        time.sleep(2)

        text = driver.find_element(By.ID, "tv_position_name").text
        listText = list(text)

        if a in listText:
            driver.find_element(By.ID, "view_job_card").click()

            # 过滤不活跃的
            if driver.find_element(By.ID, "boss_label_tv").text == "半年前活跃":
                driverBack("iv_back")
                continue

            # 过滤已经沟通过的
            if driver.find_element(By.ID, "btn_chat").text == "继续沟通":
                driverBack("iv_back")
                continue

            # 过滤详情页标题信息
            pageText = driver.find_element(By.ID, "tv_job_name").text
            listPageText = list(pageText)

            if a in listPageText:
                time.sleep(2)

                # 点击立即沟通
                driver.find_element(By.ID, "btn_chat").click()

                # 发送打招呼语
                driver.find_element(By.CLASS_NAME, "android.widget.EditText").send_keys(
                "你好，我有相关工作经验，方便沟通下吗？")
                driver.find_element(By.XPATH,
                "//android.widget.RelativeLayout/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.ImageView").click()

                time.sleep(2)

                # 点击返回
                driverBack("iv_back")

                time.sleep(2)

                # 再次返回
                driverBack("iv_back")

            else:
                driverBack("iv_back")


if __name__ == '__main__':
    for i in range(1,4):
        try:
            main()
        except Exception as e:
            print(e)